package com.tengju.data.infrastructure.repository.data.subject;

import com.tengju.data.domain.model.clickhouse.subject.DwsSubjectSettleRepository;
import com.tengju.data.domain.model.clickhouse.subject.SubjectSkuStatistics;
import com.tengju.data.domain.model.clickhouse.subject.SubjectStatistics;
import com.tengju.data.domain.shared.BasePage;
import com.tengju.data.infrastructure.persistence.mybatis.dataobject.SubjectSkuStatisticsDO;
import com.tengju.data.infrastructure.persistence.mybatis.dataobject.SubjectStatisticsDO;
import com.tengju.data.infrastructure.persistence.mybatis.mapper.data.custom.DwsSubjectSettleViewMapper;
import com.tengju.data.infrastructure.repository.data.subject.convert.SubjectSettleConvert;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenhang
 * @Date 2021/4/22
 */
@Repository
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class DwsSubjectSettleRepositoryImpl implements DwsSubjectSettleRepository {

    private final DwsSubjectSettleViewMapper dwsSubjectSettleViewMapper;


    @Override
    public BigDecimal summary(Integer monthInt) {
        return dwsSubjectSettleViewMapper.summaryBonus(monthInt);
    }

    @Override
    public List<SubjectStatistics> listSubjectStatistics(Integer monthInt) {
        List<SubjectStatisticsDO> subjectStatisticsDOList = dwsSubjectSettleViewMapper.listSubjectStatistics(monthInt);
        if (CollectionUtils.isEmpty(subjectStatisticsDOList)) {
            return Collections.emptyList();
        }
        return subjectStatisticsDOList.stream()
                .map(SubjectSettleConvert::toStatistics)
                .collect(Collectors.toList());
    }

    @Override
    public BasePage<SubjectSkuStatistics> listSubjectSkuStatistics(Integer month, Integer pageNo, Integer pageSize) {
        pageNo = Math.max(pageNo - 1 ,0) * pageSize;
        BasePage<SubjectSkuStatistics> result = new BasePage<>();
        List<SubjectSkuStatisticsDO> subjectSkuStatisticsDOList = dwsSubjectSettleViewMapper.listSubjectSkuStatistics(month,pageNo,pageSize);
        Integer count = dwsSubjectSettleViewMapper.countSubjectSku(month);
        if (CollectionUtils.isEmpty(subjectSkuStatisticsDOList)) {
            result.setTotal(0);
            return result;
        }
        result.setTotal(count);
        List<SubjectSkuStatistics> subjectSkuStatisticsList = subjectSkuStatisticsDOList.stream()
                .map(SubjectSettleConvert::toSkuStatistics)
                .collect(Collectors.toList());
        result.setDatas(subjectSkuStatisticsList);
        return result;
    }
}
